﻿using EMoney.IStock.Client.Business.HD;
using EMoney.IStock.Client.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EMoney.IStock.Client.Business.QQ;
using EMoney.IStock.Client.Business;
using System.Text;
using EMoney.IStock.Client.Models.QQ;
using QConnectSDK.Context;
using EMoney.IStock.Client.Business.JRPT;
using EMoney.IStock.Client.Framework.ssoaccess;

namespace EMoney.IStock.Client.Web.Controllers
{
    public class FocusController : Controller
    {
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            string token = Request.QueryString.ToString();
            if (token.Contains("&"))
            {
                if (token.Contains("rand=") && token.Contains("token="))
                {
                    string tmptoken = token.Substring(token.IndexOf("rand="));
                    if (tmptoken.Contains("bata="))
                    {
                        string batatok = tmptoken.Substring(tmptoken.IndexOf("bata="));
                        if (!string.IsNullOrEmpty(batatok) && batatok.Contains("&"))
                        {
                            tmptoken = tmptoken.Replace(batatok.Substring(batatok.IndexOf('&')), "");
                        }
                    }
                    token = tmptoken;

                }
                else
                {
                    token = "";
                }
            }
            else
            {
                token = "";
            }
            ViewBag.Token = token;
            base.OnActionExecuted(filterContext);
        }

        FocusBll bll = new FocusBll();
        /// <summary>
        /// 个股聚焦更新
        /// </summary>
        /// <returns></returns>
        public string UpdateFocus()
        {
            FocusBll.TaskUpdateFocusStockList();
            return "个股聚焦更新成功";
        }

        #region 错误页面

        /// <summary>
        /// 宣传页面
        /// </summary>
        /// <returns></returns>
        public ActionResult WelCome()
        {
            return View();
        }

        /// <summary>
        /// 登录错误页面
        /// </summary>
        /// <returns></returns>
        public ActionResult LoginError()
        {
            return View();
        }

        #endregion

        /// <summary>
        /// 客户端调用接口，检查用户是否有订阅信息
        /// </summary>
        /// <returns></returns>
        public string checkusermsg()
        {
            string msg = "";
            if (ConfigHelper.IsEmRss == "0")
            {
                return "{|*0*|}{|*60*|}{|**|}{|*大赛快讯*|}";
            }
            var loginResult = IsLogin();
            if (loginResult != null)
            {
                msg = "{|*0*|}{|*60*|}{|**|}{|*大赛快讯*|}";
            }
            else
            {
                string key = "EMoney.IStock.Client.Web.rank_myrss";
                var user = GetUserInfo();
                if (user != null)
                {
                    key = key + user.UserID;
                }
                DateTime lastTime = JRPTCommCache.GetCache<DateTime>(key);
                if (lastTime == null || lastTime == DateTime.MinValue)
                {
                    lastTime = Convert.ToDateTime("2014-10-20");//订阅开始时间
                }

                if ((DateTime.Now - lastTime).TotalMinutes >= 60)
                {
                    msg = "{|*1*|}{|*60*|}{|*http://dsclient.emoney.cn/istockclient/focus/rank_myrss*|}{|*大赛快讯*|}";
                }
                else
                {

                    msg = "{|*1*|}{|*60*|}{|**|}{|*大赛快讯*|}";
                }
            }
            return msg;
        }

        /// <summary>
        /// 清除缓存
        /// </summary>
        /// <returns></returns>
        public string clearusermsg()
        {
            string uid = Request["uid"];
            string key = "EMoney.IStock.Client.Web.rank_myrss";
            var user = GetUserInfo();
            if (user != null)
            {
                key = key + user.UserID;
            }
            JRPTCommCache.Remove(key);
            return "清除成功";
        }

        /// <summary>
        /// 我的订阅列表
        /// </summary>
        /// <returns></returns>
        public ActionResult rank_myrss()
        {
            var loginResult = IsLogin();
            if (loginResult != null)
            {
                LogManager.DefaultLogger.InfoFormat("腾讯炒股大赛 登录验证没有权限 Request:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                return loginResult;
            }
            string key = "EMoney.IStock.Client.Web.rank_myrss";
            var user = GetUserInfo();
            if (user != null)
            {
                key = key + user.UserID;
            }
            JRPTCommCache.AddCache<DateTime>(key, DateTime.Now);//存入访问时间
            return View();
        }

        /// <summary>
        /// 腾讯炒股大赛
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            var loginResult = IsLogin();
            if (loginResult != null)
            {
                LogManager.DefaultLogger.InfoFormat("腾讯炒股大赛 登录验证没有权限 Request:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                return loginResult;
            }
            TB_JRPT_UserInfo user = new TB_JRPT_UserInfo();
            string uid = Request["uid"];
            if (!string.IsNullOrEmpty(uid))
            {
                user = bll.GetUserInfo(uid);
            }
            if (user != null && !string.IsNullOrEmpty(user.QQ))
            {
                ViewBag.QQState = "1";
            }
            else
            {
                ViewBag.QQState = "0";
            }

            //获取聚焦个股
            DateTime lastDate = DateTime.Now.Date;
            var list = bll.GetFocusStockList(lastDate.AddDays(-1), lastDate.AddDays(1));
            var bkLst = bll.GetFocusBlockList(lastDate.AddDays(-1), lastDate.AddDays(1));
            List<TB_FocusStock> thLst = new List<TB_FocusStock>();//当日个股聚焦
            List<TB_FocusStock> ysLst = new List<TB_FocusStock>();//昨日个股聚焦
            List<TB_FocusBlock> bLst = new List<TB_FocusBlock>();//板块聚焦
            if (list != null && list.Count > 0)
            {
                thLst = list.Where(x => x.TradeDate >= lastDate).OrderByDescending(x => x.Number).ThenByDescending(x => x.TolFund).Take(6).ToList();
                ysLst = list.Where(x => x.TradeDate < lastDate).OrderByDescending(x => x.Number).ThenByDescending(x => x.TolFund).Take(6).ToList();
            }
            if (bkLst != null && bkLst.Count > 0)
            {
                bLst = bkLst.OrderByDescending(x => x.TradeDate).ThenByDescending(x => x.Number).ThenByDescending(x => x.TolFund).Take(3).ToList();
            }
            ViewBag.thLst = thLst;
            ViewBag.ysLst = ysLst;
            ViewBag.bLst = bLst;
            //获取排行榜数据
            rank();

            return View();
        }

        /// <summary>
        /// 总排名
        /// </summary>
        /// <returns></returns>
        public ActionResult rank()
        {
            RankBll rank_bll = new RankBll();
            //int userid = TokenBll.GetUserIDByCookie();  //从Cookie中获取用户编号
            //string qq = string.Empty;
            //qq = TokenBll.GetQQByUserID(userid);
            //if (!string.IsNullOrEmpty(qq))
            //{
            //    //订阅列表
            //    //ViewBag.EmRss = rank_bll.GetEmRssList(qq);
            //}
            var type = Request["type"];
            if (type == "1")
            {
                //周排行榜
                ViewBag.RankLst = rank_bll.GetRankWeekLst();
            }
            else if (type == "2")
            {
                //日排行榜
                ViewBag.RankLst = rank_bll.GerRankDayLst();
            }
            else
            {
                type = "0";
                //总排行榜
                ViewBag.RankLst = rank_bll.GetRankLst();
            }
            ViewBag.RankType = type;
            return View();
        }

        /// <summary>
        /// 高手揭秘
        /// </summary>
        /// <returns></returns>
        public ActionResult rank_gsjm(string qq)
        {
            //持仓
            TradeBll tradeBll = new TradeBll();
            ViewBag.Stocks = tradeBll.GetStocks(qq);
            return View();
        }

        /// <summary>
        /// 高手揭秘左侧信息
        /// </summary>
        /// <param name="qq"></param>
        /// <returns></returns>
        public ActionResult rank_gsjm_left(string qq, string nickname)
        {
            TradeBll tradeBll = new TradeBll();
            //根据qq获取用户资产信息
            ViewBag.Assets = tradeBll.GetAssets(qq);

            RankBll rank_bll = new RankBll();
            QQUserInfo qquserinfo = rank_bll.GetQQUserInfo(qq);
            if (qquserinfo != null)
            {
                ViewBag.UserPic = qquserinfo.face;
            }
            else
            {
                ViewBag.UserPic = StringHelper.GetStaticFile("IStockClientStatic/jrpt/images/uncover_img01.jpg");
            }
            ViewBag.NickName = nickname;
            return View();
        }

        /// <summary>
        /// 高手揭秘 持仓
        /// </summary>
        /// <param name="qq"></param>
        /// <returns></returns>
        public ActionResult rank_gsjm_detail(string qq)
        {
            TradeBll tradeBll = new TradeBll();
            ViewBag.DealOrders = tradeBll.GetDealOrders(qq, "2014-10-01", "2024-10-01");

            return View();
        }

        /// <summary>
        /// 报名参赛
        /// </summary>
        /// <returns></returns>
        public ActionResult JRPTRegister()
        {
            var loginResult = IsLogin();
            if (loginResult != null)
            {
                LogManager.DefaultLogger.InfoFormat("腾讯炒股大赛 登录验证没有权限 Request:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                return loginResult;
            }

            var user = GetUserInfo();
            if (user != null && !string.IsNullOrEmpty(user.QQ))
            {
                return Redirect(Url.Action("RegisterCom", "Focus", new { state = "1" }));
            }
            return View();
        }

        /// <summary>
        /// 获取QQ号
        /// </summary>
        /// <param name="returnURL"></param>
        /// <returns></returns>
        public ActionResult QQ()
        {
            string returnURL = Request.Url.AbsoluteUri;
            string uid = Request["uid"];
            if (string.IsNullOrEmpty(uid))
                return Content("非法访问");
            returnURL = returnURL.Substring(0, returnURL.IndexOf("QQ?")) + "RegisterCom?uid=" + uid;

            try
            {
                var context = new QzoneContext();
                string state = Guid.NewGuid().ToString().Replace("-", "");
                Session["requeststate"] = state;
                string scope = "get_user_info,add_share,list_album,upload_pic,check_page_fans,add_t,add_pic_t,del_t,get_repost_list,get_info,get_other_info,get_fanslist,get_idolist,add_idol,del_idol,add_one_blog,add_topic,get_tenpay_addr";

                string authenticationUrl = context.GetAuthorizationUrl(state, scope);
                authenticationUrl = string.Format(authenticationUrl, Server.UrlEncode(returnURL));
                return new RedirectResult(authenticationUrl);
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(ex, "Focus>QQ 金融平台绑定QQ号异常！ [url={0}]", returnURL);
            }
            return Content("异常访问");
        }

        /// <summary>
        /// 绑定完成
        /// </summary>
        /// <returns></returns>
        public ActionResult RegisterCom(string state = "0")
        {
            string uid = Request["uid"];
            string openId = Request["openid"];
            string msg = "绑定失败，请重新绑定";
            string loginState = "0";
            if (!string.IsNullOrEmpty(openId))
            {
                string qq = "";
                try
                {
                    OAuthBll abll = new OAuthBll();
                    qq = abll.GetUserQQByOpenID(openId);
                    if (!string.IsNullOrEmpty(qq))
                    {
                        var user = bll.GetUserInfo(uid);
                        if (user != null)
                        {
                            if (string.IsNullOrEmpty(user.QQ))
                            {
                                user.UserID = uid;
                                user.OpenID = openId;
                                user.QQ = qq;
                                //绑定QQ号存入数据库
                                user = bll.AddUserInfo(user, ref msg);
                                if (user != null && string.IsNullOrEmpty(msg))
                                {
                                    string key = "EMoney.IStock.Client.Web.FocusController.SSODecrypt" + uid;
                                    string id = GetUserCookieID();
                                    key = key + id;

                                    //更新缓存数据
                                    int mi = Convert.ToInt32((DateTime.Now.Date.AddDays(1) - DateTime.Now).TotalMinutes);
                                    JRPTCommCache.AddCache<TB_JRPT_UserInfo>(key, user, mi);
                                    CookieHelper.AddCookie("EMoney_FocusController_SSODecrypt", id, DateTime.Now.Date.AddDays(1));
                                    msg = "恭喜您，绑定成功";
                                    loginState = "1";
                                }
                            }
                            else
                            {
                                msg = "账号已绑定过QQ号码";
                                loginState = "1";
                            }
                        }
                        else
                        {
                            msg = "绑定失败，账号不存在";
                        }
                    }
                    else
                    {
                        msg = "绑定失败，QQ号码无法获取";
                    }
                }
                catch (Exception ex)
                {
                    LogManager.DefaultLogger.Error(ex, "Focus>GetUserQQByOpenID 金融平台获取QQ号异常！ [openID={0}]", openId);
                    msg = "绑定失败，QQ号码无法获取";
                }
            }
            else if (state == "1")
            {
                loginState = "1";
                msg = "账号已绑定过QQ号码";
            }
            ViewBag.Msg = msg;
            ViewBag.LoginState = loginState;
            ViewBag.UserID = uid;
            return View();
        }

        #region SSO登录验证

        /// <summary>
        /// 是否登录
        /// </summary>
        /// <returns></returns>
        bool CheckLogin()
        {
            bool bz = true;
            if (ConfigHelper.IsOnline != "0")
            {
                string uid = Request["uid"];
                string lastUserID = CookieHelper.GetCookies("loginUserID" + uid);
                if (string.IsNullOrEmpty(uid))
                {
                    if (string.IsNullOrEmpty(lastUserID))
                    {
                        bz = false;
                    }
                    CookieHelper.AddCookies("loginUserID" + uid, lastUserID);
                }
                else
                {
                    TB_JRPT_UserInfo user = SSODecrypt(uid);
                    if (user == null)
                    {
                        bz = false;
                        CookieHelper.AddCookies("loginUserID" + uid, "");
                    }
                    else
                    {
                        CookieHelper.AddCookies("loginUserID" + uid, user.UserID);
                    }
                }
            }
            else
            {
                CookieHelper.AddCookies("loginUserID", "");
            }
            return bz;
        }

        /// <summary>
        /// 获取当前用户
        /// </summary>
        /// <returns></returns>
        TB_JRPT_UserInfo GetUserInfo()
        {
            string uid = Request["uid"];
            TB_JRPT_UserInfo user = null;
            if (ConfigHelper.IsOnline != "0")
            {
                if (!string.IsNullOrEmpty(uid))
                {
                    user = SSODecrypt(uid);
                }
            }
            return user;
        }

        /// <summary>
        /// 获取用户的CookieID
        /// </summary>
        /// <returns></returns>
        string GetUserCookieID()
        {
            var cookie = CookieHelper.GetCookie("EMoney_FocusController_SSODecrypt");
            string id = "";
            if (!string.IsNullOrEmpty(cookie) && cookie.Length == 36)
            {
                id = cookie;
            }
            else
            {
                id = Guid.NewGuid().ToString();
            }
            return id;
        }

        /// <summary>
        /// SSO验证
        /// </summary>
        /// <returns></returns>
        TB_JRPT_UserInfo SSODecrypt(string uid)
        {
            string key = "EMoney.IStock.Client.Web.FocusController.SSODecrypt" + uid;
            string id = GetUserCookieID();
            key = key + id;
            var model = JRPTCommCache.GetCache<TB_JRPT_UserInfo>(key);
            if (model == null || model.UserID != uid)
            {
                UserLoginInfo user = new UserLoginInfo();
                access service = new access();
                service.Url = ConfigHelper.SSOAccess;

                var queryString = System.Web.HttpContext.Current.Request.QueryString.ToString();
                try
                {
                    user = service.GetUserInfo(queryString, "127.0.0.1", 0);
                }
                catch (Exception ex)
                {
                    LogManager.DefaultLogger.Error(ex, "SSO验证错误 GetUserInfo({1},{2},{3}) Error:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), queryString, "127.0.0.1", "0");

                    throw new Exception("身份验证失败");
                }

                //判断SSO解密用户是否是同一用户
                if (user != null && user.Uid == uid)
                {
                    //判断SSO是否登录
                    if (!user.Checked)
                    {
                        //判断是否是内网账号
                        if (!IsAllPower(user.UserName))
                        {
                            JRPTCommCache.Remove(key);
                            return null;
                        }
                    }
                }
                else
                {
                    JRPTCommCache.Remove(key);
                    return null;
                }

                string msg = "";
                //检查用户信息是否入库
                model = bll.GetUserInfo(uid);
                if (model == null)
                {
                    model = new TB_JRPT_UserInfo();
                    model.UserID = user.Uid;
                    model.EMName = user.UserName;
                    model.PID = user.Pid;
                    model = bll.AddUserInfo(model, ref msg);//添加用户信息
                }
                if (string.IsNullOrEmpty(msg))
                {
                    int mi = Convert.ToInt32((DateTime.Now.Date.AddDays(1) - DateTime.Now).TotalMinutes);
                    JRPTCommCache.AddCache<TB_JRPT_UserInfo>(key, model, mi);
                    CookieHelper.AddCookie("EMoney_FocusController_SSODecrypt", id, DateTime.Now.Date.AddDays(1));
                }
            }
            return model;
        }

        /// <summary>
        /// 获取所有内网用户
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        bool IsAllPower(string userName)
        {
            List<string> list = bll.GetAllPower();
            if (list != null && list.Count > 0)
            {
                if (list.Contains(userName))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 登录验证
        /// </summary>
        /// <returns></returns>
        public ActionResult IsLogin()
        {
            try
            {
                if (CheckLogin())
                {
                    return null;
                }
                else
                {
                    return Redirect(Url.Action("LoginError", "Focus", new { errorMsg = "登录验证失败，请重新登录" }));
                }
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(ex, "登录验证错误 CheckLogin() Error:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                return Redirect(Url.Action("LoginError", "Focus", new { errorMsg = ex.Message }));
            }
        }

        #endregion
    }
}
